
<?php
class PNUserAdvert extends PNObjectEx {
  function PNUserAdvert($init=null, $where='')
  {
    $this->PNObject();

    $this->_objType       = 'innoadvert_advert';
    $this->_objField      = 'id';
    $this->_objPath       = 'form';

    $this->_objJoin[]     = array ( 'join_table'  =>  'innoadvert_categories',
                            'join_field'          =>  array('name'),
                            'object_field_name'   =>  array('categories_name'),
                            'compare_field_table' =>  'categories_id',
                            'compare_field_join'  =>  'id');

    $this->_objJoin[]     = array ( 'join_table'  =>  'innoadvert_subcategories',
                            'join_field'          =>  array('name'),
                            'object_field_name'   =>  array('subcategories_name'),
                            'compare_field_table' =>  'subcategories_id',
                            'compare_field_join'  =>  'id');

    $this->_objJoin[]     = array ( 'join_table'  =>  'innoadvert_province',
                            'join_field'          =>  array('name'),
                            'object_field_name'   =>  array('province_name'),
                            'compare_field_table' =>  'province_id',
                            'compare_field_join'  =>  'id');

    $this->_init($init, $where);
  }

  function insertPostProcess(){
    Loader::loadClass('DataUtilEx', "modules/InnoAdvert/pnincludes");
    $id = DBUtil::getInsertID ($this->_objType, $this->_objField);
    if ($id){
      ///////////set ref_id/////////
      //////get category prefix/////
      //$cate = DBUtil::selectFieldByID('innoadvert_categories','id',$this->_objData['categories_id']);
      //$user = DataUtilEx::fillString($this->_objData['user_id'],2,'0');
      //$ref_id = DataUtilEx::fillString($id,5,'0', $cate . $user);
      $object = array('id'=>$id);
      DBUtil::updateObject($object,$this->_objType);
      $this->uploadFiles($id);
      $this->checkHasFile($id);
    }
  }

  function updatePostProcess(){
    //set thumb to image status
    $form = FormUtil::getPassedValue ('form', false );
    $id = $this->_objData['id'];
    //set image thumb
    $firstimage_id = $form['firstimage'];
    if ($firstimage_id && $id){
      //clear status
      $object = array('status' => 0);
      $where = "WHERE img_advertise_id = '$id'";
      DBUtil::updateObject($object,'innoadvert_images',$where);
      //set thumb
      $object = array('id' => $firstimage_id , 'status' => 1);
      DBUtil::updateObject($object,'innoadvert_images');

      //Set first image to inventory table
      $columnArray = array('imagename','thumbname');
      $firstimage = DBUtil::selectObject('innoadvert_images' ,
                                              "WHERE img_advertise_id = '$id' AND img_status = 1",
                                              $columnArray
                                            );
      $object = array('firstfilename'=>$firstimage['imagename'] , 
                      'firstthumbname'=>$firstimage['thumbname']);
      $where  = " adv_id = ".$id;
      DBUtil::updateObject($object,'innoadvert_advert',$where);
    }

    //delete image
    foreach($form['file_delete'] as $delete_id){
      //Delete file from directory
      $columnArray = array('part','imagename','thumbname');
      $objectImageName = DBUtil::selectObject('innoadvert_images',"img_id = '$delete_id)'",
                                              $columnArray);

                    unlink($data['part'].$data['imagename']);
                    unlink($data['part'].$data['thumbname']);

      DBUtil::deleteObjectByID('innoadvert_images',$delete_id);
    }
    $this->uploadFiles($id);
    $this->checkHasFile($id);
  }


  function deletePreProcess(){

    $id = $this->_objData['id'];
    if ($id){
      //Delete file from directory
      $objects = array('part','imagename','thumbname');
      $objectImagename = DBUtil::selectObjectArray('innoadvert_images',"WHERE img_advertise_id = '$id'"
                                                        , '',-1, -1,'', null, null, $objects);
      foreach($objectImagename as $data){
        unlink($data['part'].$data['imagename']);
        unlink($data['part'].$data['thumbname']);
        //unlink('resource/innoadvert_upload/images/advert/'.$data['thumbname']);
      }

     //delete image
      DBUtil::deleteWhere('innoadvert_images',"WHERE img_advertise_id = '$id'");
    }
  }
  

/*
  
  function selectExtendResult(){
    $id = FormUtil::getPassedValue ('id', false );
    $result = array();
    $objects = array('id', 'path', 'filename', 'filesize', 'filetype');
    if ($id){
      $result['files'] = DBUtil::selectObjectArray('innoadvert_files' , "WHERE fil_doc_id = '$id' AND fil_path = 'pnTemp/innoadvert_upload/'" ,
                                                     'fil_id',-1, -1,'', null, null, $objects);

    }
    $objectsSubCategories = array('id', 'name');
    $result['subcategories'] = DBUtil::selectObjectArray('innoadvert_subcategories' , " " ,
                                                     '',-1, -1,'', null, null, $objectsSubCategories);


    return $result;
  }
*/

  function uploadFiles($id){
    $count = DBUtil::selectObjectCount('innoadvert_images' , "WHERE img_advertise_id  = '$id'");

    if ($id && in_array(0,$_FILES['images']['error'])){
      $images = $_FILES['images'];
      $imagespath = "resource/innoadvert_upload/images/advert/";
      foreach ($images["error"] as $key => $error){
        if ($error == 0){
            //Gennerate next id
            $image_id = DBUtil::selectFieldMax( 'innoadvert_images', 'id', 'MAX', '');
            if($image_id == null){
              $next_id = 1;
            }else{
              $next_id = $image_id+1;
            }

            $tmp_name = $images["tmp_name"][$key];
            $fliename = $images["name"][$key];

////////////////////////// get the extension of the file in a lower case format/////////////////////////////////////
            $filename = stripslashes($fliename);
            $i = strrpos($filename,".");
            if (!$i) { return ""; }
            $l = strlen($filename) - $i;
            $ext = substr($filename,$i+1,$l);
            $extension = strtolower($ext);

////////////////////////////generate new file&path//////////////////////////////////////////////////////////////////
            $rootname       = $next_id.time().".".$extension;
            $filename_temp  = "images_".$id.$rootname;
            $thumbname_temp = "thumbs_".$id.$rootname;
            $imgpath        = $imagespath.$filename_temp;
            $tmbpath        = $imagespath.$thumbname_temp;

/////////////////////////Copy images to directory///////////////////////////////////////////////////////////////////
            copy($tmp_name,$imgpath);

            if(strcmp("jpg",$extension)==0)
              $src_img=imagecreatefromjpeg($tmp_name);

            if(strcmp("jpeg",$extension)==0)
              $src_img=imagecreatefromjpeg($tmp_name);

            if(strcmp("png",$extension)==0)
              $src_img=imagecreatefrompng($tmp_name);

            if(strcmp("gif",$extension)==0)
              $src_img=imagecreatefromgif($tmp_name);

            if(strcmp("bmp",$extension)==0)
              $src_img=imagecreatefromwbmp($tmp_name);

            //gets the dimmensions of the image
            $old_x=imageSX($src_img);
            $old_y=imageSY($src_img);

            // next we will calculate the new dimmensions for the thumbnail image
            // the next steps will be taken:
            // 1. calculate the ratio by dividing the old dimmensions with the new ones
            // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
            // and the height will be calculated so the image ratio will not change
            // 3. otherwise we will use the height ratio for the image
            // as a result, only one of the dimmensions will be from the fixed ones
            $new_w = 200;
            $new_h = 150;
            $ratio1=$old_x/$new_w;
            $ratio2=$old_y/$new_h;
            if($ratio1>$ratio2) {
              $thumb_w=$new_w;
              $thumb_h=$old_y/$ratio1;
            }else{
              $thumb_h=$new_h;
              $thumb_w=$old_x/$ratio2;
            }

            // we create a new image with the new dimmensions
            $dst_img   = ImageCreateTrueColor($thumb_w,$thumb_h);

            // resize the big image to the new created one
            $thumb = imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);

            $thumbsize = '1000';
            $thumbtype = $filetype;

            // output the created image to the file. Now we will have the thumbnail into the file named by $filename
            if(strcmp("png",$extension)==0){
              imagepng($dst_img,$tmbpath);
            }else if(strcmp("jpg",$extension)==0){
              imagejpeg($dst_img,$tmbpath);
            }else if(strcmp("jpeg",$extension)==0){
              imagejpeg($dst_img,$tmbpath);
            }else if(strcmp("bmp",$extension)==0){
              imagewbmp($dst_img,$tmbpath);
            }else if(strcmp("gif",$extension)==0){
              imagegif($dst_img,$tmbpath);
            }else {
              imagejpeg($dst_img,$tmbpath);
            }

            //destroys source and destination images.
            imagedestroy($dst_img);
            imagedestroy($src_img);

            $objects = array(
                            'id'            => $next_id,
                            'path'          => $imagespath,
                            'advertise_id'  => $id,
                            'imagename'     => $filename_temp,
                            'thumbname'     => $thumbname_temp, 
                            'status'        => 1
                           );

          DBUtil::insertObject($objects,'innoadvert_images');

        }
      }
      //Set default images
      if ($id && $count==0){
        $object = array('firstfilename'=>$filename_temp , 'firstthumbname'=>$thumbname_temp);
        $where  = "adv_id = ".$id;
        DBUtil::updateObject($object,'innoadvert_advert',$where);
      }
    }
  }

  function checkHasFile($id){
    $count = DBUtil::selectObjectCount( 'innoadvert_images', 'img_advertise_id = '.$id, 'id', true, null);
    if ($count && $id){
      $object = array('has_file' => $count);
      DBUtil::updateObject( $object, 'innoadvert_advert', 'adv_id = '.$id);
    }
  }

}
